#include "EventLoop.hpp"
#include "Listener.hpp"
#include "BlockQueue.hpp"
#include "Calculator.hpp"

Calculator calculator;

void DeafaultOnMessage(std::weak_ptr<Connection> conn)
{
    auto connection = conn.lock();
    lg(Debug, "上层收到了数据: %s", connection->Inbuffer());
    // 对报文进行处理
    std::string resp = calculator.Handler(connection->Inbuffer());
    if (resp.empty())
        return;
    lg(Debug, "%s", resp.c_str());
    connection->AppendOutbuffer(resp);
    connection->_el_ptr.lock()->Sender(connection);
}


void *Consume(void *args)
{

}

int main()
{
    // std::shared_ptr<TcpServer> psvr(new TcpServer(8888, DeafaultOnMessage));
    // psvr->Init();
    // psvr->Loop();

    // 创建listener
    Listener listener(8888);
    // 将listener接收连接的工作交给base_reactor 主线程
    std::shared_ptr<EventLoop> base_reactor(new EventLoop(DeafaultOnMessage));
    base_reactor->AddConnection(listener._listensock_ptr->Fd(), EVENT_IN,
                                std::bind(Listener::Accept, &listener, std::placeholders::_1), nullptr, nullptr);

    // 创建阻塞队列
    std::shared_ptr<BlockQueue<int>> bq(new BlockQueue<int>);

    // 创建消费者线程
    pthread_t c[5];
    for (int i = 0; i < 5; ++i)
    {
        pthread_create(c + i, nullptr, Consume, nullptr);
    }

    // 开启主reactor事件循环，将接收到的sockfd放入到主reactor的数组中
    base_reactor->Loop();


    for (int i = 0; i < 5; ++i)
    {
        pthread_join(c[i], nullptr);
    }

    return 0;
}